import {IS_FOR_WX} from "../../AppConfig";

if (cc.sys.platform === cc.sys.WECHAT_GAME && IS_FOR_WX) {
  let sendLogEvent = require("./WechatAldLog").sendLogEvent;
  let {showCurrentBanner, hideCurrentBanner} = require("./WechatBannerAd");
  
  const INTERSTITIAL_AD_ID = "";
  
  let _interstitialAd;
  let _adLoad = false;
  let _isWaitingInterstitialAd = false;
  let createInterstitialAd = function () {
    if (wx.createInterstitialAd !== undefined) {
      _interstitialAd = wx.createInterstitialAd({adUnitId: INTERSTITIAL_AD_ID});
      
      _interstitialAd.onLoad(() => {
        console.log('插屏广告加载成功');
        _adLoad = true;
      });
      _interstitialAd.onError(err => {
        _adLoad = false;
        console.log('插屏广告加载错误', err);
      });
      _interstitialAd.onClose((res) => {
        console.log('插屏广告关闭', res);
        _adLoad = false;
        showCurrentBanner();
      });
    }
  };
  
  createInterstitialAd();  //预加载一个插屏广告
  
  /**
   * 插屏广告是否已经加载成功
   * @param logKey
   * @returns {boolean}
   */
  let isInterstitialAdLoad = function (logKey) {
    if (logKey !== undefined) {
      if (_adLoad) {
        sendLogEvent("无可用插屏广告 - " + logKey);
      }
    }
    return _adLoad;
  };
  
  /**
   * 显示插屏广告
   * @param logKey
   * @param callback
   */
  let showInterstitialAd = function (logKey, callback) {
    if (!Global.SwitchSettings.getEnableInterstitialAd()) {
      sendLogEvent("插屏广告被设为关闭");
      callback && callback();
      return;
    }
    if (logKey !== undefined) {
      sendLogEvent("插屏广告开始 - " + logKey);
    }
    if (_interstitialAd !== undefined) {
      if (_adLoad) {
        _isWaitingInterstitialAd = true;
        _interstitialAd.show().then((res) => {
          _isWaitingInterstitialAd = false;
          if (logKey) {
            sendLogEvent("插屏广告成功" + logKey);
          }
          console.log('插屏广告成功', res);
          
          hideCurrentBanner();
          callback && callback();
        }).catch((err) => {
          _isWaitingInterstitialAd = false;
          console.log('激励插屏广告显示失败', err);
          callback && callback();
        })
      }
    } else {
      callback && callback();
    }
  };
  
  let isWaitingInterstitialAd = function () {
    return _isWaitingInterstitialAd;
  };
  module.exports = {
    showInterstitialAd,
    isInterstitialAdLoad,
    isWaitingInterstitialAd,
  }
}